﻿#include "mainwindow.h"
#include "http/http.h"
#include "common_log.h"




MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);

	server = new Http("http:://127.0.0.1:8089");
	ServerInter inter = {};
	inter.name = "hello";
	inter.log = true;
	inter.callback = [](const QByteArray& req, QByteArray& ans) {
		log_trace("{}", req);
		ans = req;
	};
	server->RegisterInterface("/hellow", inter);
	
	log_trace("123");
	m_th = new std::thread(&MainWindow::RunServer, this);
	m_th->detach();

	QString dbpath = QCoreApplication::applicationDirPath() + "/config/robot.db";
	m_db = DataBase::CreateDataBase(dbpath);
	if (m_db == nullptr) {
		log_error("数据库创建失败");
		ui.textEdit_2->clear();
		ui.textEdit_2->append("数据库打开失败");
	}
}

MainWindow::~MainWindow()
{
}
void MainWindow::RunServer()
{
	server->Start(8088);
}
void MainWindow::on_pushButton_clicked()
{
	QString path = ui.lineEdit->text();
	QByteArray data = ui.textEdit->toPlainText().toUtf8();
	QByteArray ans;
	wcs_send(path, ans, data);
	log_trace("ans:{}", ans);
	
}
void MainWindow::on_pushButton_3_clicked()
{
	QString name = ui.lineEdit_2->text();
	bool ret = m_db->CreateDBTable(name);
	if (!ret) {
		log_trace("数据库 create {} failed", name);
		ui.textEdit_2->clear();
		ui.textEdit_2->append("数据表创建失败");
	}
}
// xie
void MainWindow::on_pushButton_7_clicked()
{
	QString name = ui.lineEdit_2->text();
	int id = ui.lineEdit_4->text().toInt();
	QByteArray data = ui.textEdit_2->toPlainText().toUtf8();
	auto ret = m_db->AddData(name, id, data);
	if (!ret) {
		log_trace("数据库 add {} failed", data);
		ui.textEdit_2->clear();
		ui.textEdit_2->append("数据写入失败");
	}
}
// read
void MainWindow::on_pushButton_6_clicked()
{
	QString name = ui.lineEdit_2->text();
	int id = ui.lineEdit_4->text().toInt();
	auto ret = m_db->ReadDataById(name, id);
	ui.textEdit_2->clear();
	ui.textEdit_2->append("读取的新数据：");
	if (ret.size() <= 0) {
		log_trace("read failed");
		ui.textEdit_2->append("读取失败");
		return;
	}
	for (auto& iter : ret) {
		ui.textEdit_2->append(iter);
	}
}
//update
void MainWindow::on_pushButton_8_clicked()
{
	QString name = ui.lineEdit_2->text();
	int id = ui.lineEdit_4->text().toInt();
	QByteArray data = ui.textEdit_2->toPlainText().toUtf8();
	auto ret = m_db->UpdateData(name, id, data);
	if (!ret) {
		log_trace("数据库 UpdateData {} failed", data);
		ui.textEdit_2->clear();
		ui.textEdit_2->append("数据更新失败");
	}
}
// delete
void MainWindow::on_pushButton_13_clicked()
{
	QString name = ui.lineEdit_2->text();
	int id = ui.lineEdit_4->text().toInt();
	auto ret = m_db->DeleteData(name, id);
	if (!ret) {
		log_trace("数据库 DeleteData failed");
		ui.textEdit_2->append("数据删除失败");
	}
}
